<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="广告名称">
            <a-input v-decorator="['adName']" placeholder="请输入广告名称" />
          </a-form-item>
          <a-form-item label="系统类型">
            <a-select allowClear v-decorator="['type', { initialValue: 0 }]">
              <a-select-option :value="0">全部</a-select-option>
              <a-select-option v-for="opt in adBindType.getData()" :key="opt.value" :value="opt.value">{{
                opt.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="新系统书籍名称">
            <a-input v-decorator="['name']" placeholder="请输入新系统书籍名称" />
          </a-form-item>
          <a-form-item label="旧系统书籍名称">
            <a-input v-decorator="['dirName']" placeholder="请输入旧系统书籍名称" />
          </a-form-item>

          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
          </a-form-item>
        </a-form>
      </a-row>

      <!-- 操作板块 -->
      <div class="row-item-tab clearfix">
        <a-button class="fl-l" type="primary" icon="plus" @click="handleBatchBind">绑定</a-button>
        <a-button
          class="fl-l"
          type="danger"
          icon="delete"
          :disabled="!hasSelected"
          :loading="isLoading"
          @click="handleDelete(selectedRowKeys)"
          >批量删除</a-button
        >
        <!-- <a-upload
          name="iFile"
          class="fl-l"
          :accept="'zip'"
          :customRequest="onUpload"
          :multiple="false"
          :showUploadList="false"
        >
          <a-button icon="cloud-upload"
                    type="primary">批量导入旧数据广告</a-button>
        </a-upload>
        <a-button
          class="fl-l"
          @click="download"
        >下载旧数据广告导入模版</a-button> -->
      </div>
    </div>
    <s-table
      ref="table"
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
    >
      <span slot="status" slot-scope="text, item">
        <a-tag class="cur-p" :color="text === 10 ? 'green' : 'red'" @click="handleUpdateStatus(item.id, text)">{{
          text === 10 ? '正常' : '停用'
        }}</a-tag>
      </span>
      <span slot="adStatus" slot-scope="text, item">
        <a-tag class="cur-p" :color="text === 10 ? 'green' : 'red'">{{ text === 10 ? '正常' : '停用' }}</a-tag>
      </span>
      <span slot="type" slot-scope="text, item">
        {{ adBindType.getNameByValue(text) }}
      </span>
      <span slot="name" slot-scope="text, item">
        <a v-if="item.type === adBindType.OLD.value" target="_blank" :href="item.oldName" class="book-name">{{
          item.oldName
        }}</a>
        <div v-else class="book-name">{{ item.name }}</div>
      </span>
      <!-- 操作 -->
      <span class="actions" slot="action" slot-scope="text, item">
        <a style="color: red" v-action:delete @click="handleDelete([item.id])">删除</a>
        <a v-action:changeAd @click="handleChangeAd(item)">修改广告</a>
      </span>
    </s-table>
    <changeAd ref="changeAd" @handleSubmit="handleRefresh(false)"></changeAd>
  </a-card>
</template>

<script>
import * as Api from '@/api/ad'
import { STable } from '@/components'
import adActionType from '@/common/enum/adActionType'
import adBindType from '@/common/enum/adBindType'
import changeAd from './modules/changeAd'
export default {
  name: 'Index',
  components: {
    STable,
    changeAd
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length
    }
  },
  data() {
    return {
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      selectedRowKeys: [],
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      adActionType,
      adBindType,
      tplUrl: process.env.VUE_APP_BASE_API + 'temp/menuTemplate.xlsx',
      // 表头
      columns: [
        {
          title: '广告名称',
          dataIndex: 'adName'
        },
        {
          title: '系统类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '书籍名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },

        {
          title: '当前状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '广告状态',
          dataIndex: 'adStatus',
          scopedSlots: { customRender: 'adStatus' }
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (param) => {
        return Api.oldList({ ...param, ...this.queryParam }).then((response) => response.data)
      }
    }
  },
  created() {},
  methods: {
    /**
     * 删除记录
     */
    handleDelete(id) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk() {
          return Api.oldDel({ id })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    handleChangeAd(item) {
      this.$refs.changeAd.open(item)
    },
    onSelectChange(val) {
      this.selectedRowKeys = val
    },
    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },

    onUpload(info) {
      if (!/csv/.test(info.file.type)) {
        this.$message.error('请按照模版上传文件')
        return
      }
      this.isLoading = true
      // 构建上传参数
      const formData = new FormData()
      formData.append('iFile', info.file)
      const app = this
      // 开始上传
      Api.oldBindImport(formData)
        .then(() => {
          app.$message.success('导入成功')
          app.handleRefresh(true)
        })
        .finally(() => {
          this.isLoading = false
        })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      this.$refs.table.refresh(bool)
    },
    // 修改状态()
    handleUpdateStatus(id, state) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要' + (state === 10 ? '停用' : '启用') + '该记录吗?',
        onOk() {
          return Api.oldChangeStatus({ id })
            .then((result) => {
              // 显示成功
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    download() {
      const a = document.createElement('a')
      a.href = this.$store.getters['domain'] + '/temp/旧书籍广告导入模版.csv'
      a.target = '_blank'
      a.click()
      a.remove()
    },
    handleBatchBind() {
      this.$router.push({ path: '/ad/bind' })
    }
  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}
.book-name {
  width: 200px;
  word-break: break-all;
  word-wrap: break-word;
  white-space: initial;
}
</style>
